package com.chcit.mobile.mvp.home;

import android.animation.Animator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatCheckedTextView;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.chcit.mobile.helper.ColorChooserDialog;
import com.chcit.mobile.mvp.LoginActivity;
import com.chcit.mobile.mvp.TaskActivity;
import com.chcit.mobile.mvp.setting.SettingsActivity;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.alibaba.fastjson.JSONObject;
import com.chcit.custom.view.dialog.DialogPlus;
import com.chcit.custom.view.loader.LoadingDialog;
import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.custom.view.toolbar.ImageViewOptions;
import com.chcit.custom.view.util.DialogUtil;
import com.chcit.custom.view.widget.ResideLayout;
import com.chcit.custom.view.widget.theme.ColorRelativeLayout;
import com.chcit.custom.view.widget.theme.ColorUiUtil;
import com.chcit.custom.view.widget.theme.Theme;
import com.chcit.mobile.BuildConfig;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.SupportToolbarActicity;
import com.chcit.mobile.common.HttpMethodContains;
import com.chcit.mobile.app.utils.BarcodeUtil;
import com.chcit.mobile.app.utils.SharedPreUtils;
import com.chcit.mobile.app.utils.ThemeUtils;
import com.chcit.mobile.common.DataKeys;
import com.chcit.mobile.di.component.DaggerHomeComponent;
import com.chcit.mobile.di.module.HomeModule;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.helper.UpdateAppHttpUtil;
import com.chcit.mobile.helper.recycler.GridSpacingItemDecoration;
import com.chcit.mobile.mvp.common.contract.HomeContract;
import com.chcit.mobile.mvp.common.model.CommonModel;
import com.chcit.mobile.mvp.common.presenter.HomePresenter;
import com.chcit.mobile.mvp.entity.HomeItem;
import com.chcit.mobile.mvp.entity.MainMenuBean;
import com.chcit.mobile.mvp.common.adapter.LogLevelAdapter;
import com.elvishew.xlog.LogLevel;
import com.elvishew.xlog.XLog;
import com.jess.arms.base.app.ConfigKeys;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.xuexiang.xui.widget.toast.XToast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class HomeActivity extends SupportToolbarActicity<HomePresenter> implements HomeContract.View, ColorChooserDialog.ColorCallback {

    private static final int SETTING_REQUEST_CODE = 11112;
    private static int REQUEST_CODE = 11111;
    @BindView(R.id.iv_avatar)
    AppCompatImageView mIvAvatar;
    @BindView(R.id.tv_desc)
    TextView mTvDesc;
    @BindView(R.id.top_menu)
    LinearLayout mTopMenu;
   /* @BindView(R.id.rv_menu)
    RecyclerView mRvMenu;*/
    @BindView(R.id.tv_theme)
    TextView mTvTheme;
    @BindView(R.id.tv_setting)
    TextView mTvSetting;

    @BindView(R.id.menu)
    ColorRelativeLayout mMenu;
//    @BindView(R.id.container)
//    FrameLayout mContainer;
    @BindView(R.id.resideLayout)
    ResideLayout mResideLayout;
    @BindView(R.id.rv_home_menu)
    RecyclerView rvMeue;
    @BindView(R.id.rv_list)
    RecyclerView mRecyclerView;
//    @BindView(R.id.ll_home_menu_first)
//    LinearLayoutCompat llLogLevel;
//    @BindView(R.id.ll_home_menu_second)
//    LinearLayoutCompat llUpdate;
//    @BindView(R.id.ll_home_menu_third)
//    LinearLayoutCompat llSetting;

    @Inject
    RecyclerView.LayoutManager mLayoutManager;
    @Inject
    HomeAdapter homeAdapter;
    @Inject
    CommonModel commonModel;
    @Inject
    RxErrorHandler mErrorHandler;
    private List<MainMenuBean> menuBeans = new ArrayList<>();

    // 再点一次退出程序时间设置
    private static final long WAIT_TIME = 2000L;
    private long TOUCH_TIME = 0;
    private DialogPlus dialog;
    private MenuAdapter menuAdapter;
    private boolean onTaskOFF;

    @Override
    public void onBackPressedSupport() {

        // 默认flase，继续向上传递
        if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) {
           finish();
        } else {
            TOUCH_TIME = System.currentTimeMillis();
            Toast.makeText(this, "双击退出程序", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerHomeComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .homeModule(new HomeModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_home; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @SuppressLint("CheckResult")
    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        showLoading();
        mCommonToolbar.getLeftMenuView(0).setOnClickListener(l->{
            mResideLayout.openPane();
        });
        mCommonToolbar.getLeftMenuView(1).setOnClickListener(l->{
            mResideLayout.openPane();
        });;
        mCommonToolbar.setTitleText(HttpClientHelper.getSelectWareHouse().getName());
        mCommonToolbar.getTitleText().setOnClickListener(v->{
            HttpClientHelper.showWareSelect(this, (dialog, itemView, which, text) -> {
                ((TextView)v).setText(text);
                return false;
            });
        });
        mCommonToolbar.addRightMenuImage(ImageViewOptions.Builder()
                .setDrawableResId(R.drawable.exit_32)
                .setListener(v->{
                    new MaterialDialog.Builder(this)
                            .content("确定要退出程序吗？")
                            .positiveText("确定")
                            .negativeText("取消")
                            .onPositive((dialog, which) -> {
                               commonModel.requestOnString(HttpMethodContains.LOGIN_OUT,new JSONObject())
                                       .observeOn(AndroidSchedulers.mainThread())
                                       .doOnSubscribe(disposable -> {
                                           showLoading();
                                       })
                                       .doFinally(() -> {
                                             hideLoading();
                                             BarcodeUtil.getInstance().destroyAidBroad();
                                             ArmsUtils.exitApp();
                                             dialog.dismiss();
                                       })
                                       .subscribe(new ErrorHandleSubscriber<JSONObject>(mErrorHandler) {
                                           @Override
                                           public void onNext(JSONObject jsonObject) {
                                               XLog.i(jsonObject.toJSONString());
                                           }
                                       });

                            }).show();
                }).build());
        mIvAvatar.setImageResource(R.drawable.ic_login);
        mTvDesc.setText(SharedPreUtils.getInstance().getString(DataKeys.USERNAME.name(),"测试"));
        getMenuData();
        //mRvMenu.setLayoutManager(new LinearLayoutManager(this));
        //mainMenuAdapter = new MainMenuAdapter(menuBeans);
       // mRvMenu.setAdapter(mainMenuAdapter);
        initAdapter();
        mPresenter.getMenues();
        initLogMenue();
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        onTaskOFF =prefs.getBoolean("do_task", true);
        if(onTaskOFF&&mPresenter!=null) {
            mPresenter.queryWaitTask();
            mPresenter.start();
        }

    }

    private void getMenuData() {
        menuBeans.add(new MainMenuBean());
    }

    @OnClick({R.id.iv_avatar, R.id.tv_theme, R.id.tv_setting})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_avatar:

                break;
            case R.id.tv_theme:
                new ColorChooserDialog.Builder(this, R.string.theme)
                        .customColors(R.array.colors, null)
                        .doneButton(R.string.done)
                        .cancelButton(R.string.cancel)
                        .allowUserColorInput(false)
                        .allowUserColorInputAlpha(false)
                        .show(this);

                break;
            case R.id.tv_setting:
                startActivity(new Intent(this, LoginActivity.class));
                finish();
                break;

        }
    }

    private void checkUpdate() {
        LoadingDialog.getInstance(this).show();
        new UpdateAppManager
                .Builder()
                //当前Activity
                .setActivity(this)
                //更新地址
                .setUpdateUrl(SharedPreUtils.getInstance().getBaseUrl()+ BuildConfig.DOWN_URL)
                //实现httpManager接口的对象
                .setHttpManager(new UpdateAppHttpUtil())
                .setUpdateDialogFragmentListener(updateApp -> {

                })

                .build()
                .checkNewApp(new UpdateCallback(){
                    @Override
                    protected void noNewApp(UpdateAppBean updateApp, UpdateAppManager updateAppManager) {
                       new MaterialDialog.Builder(HomeActivity.this)
                               .content("当前版本已经是最新版本，是否重新下载最新的版本?")
                               .positiveText("确定")
                               .negativeText("取消")
                               .onPositive((dialog, which) -> {
                                   dialog.cancel();
                                   hasNewApp(updateApp,updateAppManager);
                               })
                               .show();
                    }

                    @Override
                    protected void onError(String error) {
                        DialogUtil.showErrorDialog(HomeActivity.this,error);
                    }

                    @Override
                    protected void onAfter() {
                        LoadingDialog.stop();
                    }
                });

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(this);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        XToast.info(this,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public Context getActivity() {
        return this;
    }

    @Override
    public void onColorSelection(@NonNull ColorChooserDialog dialog, int selectedColor) {
        if (selectedColor == ThemeUtils.getThemeColor2Array(this, R.attr.colorPrimary))
            return;

        if (selectedColor == getResources().getColor(R.color.colorBluePrimary)) {
            setTheme(R.style.BlueTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Blue);


        } else if (selectedColor == getResources().getColor(R.color.colorRedPrimary)) {
            setTheme(R.style.RedTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Red);

        } else if (selectedColor == getResources().getColor(R.color.colorBrownPrimary)) {
            setTheme(R.style.BrownTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Brown);

        } else if (selectedColor == getResources().getColor(R.color.colorGreenPrimary)) {
            setTheme(R.style.GreenTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Green);

        } else if (selectedColor == getResources().getColor(R.color.colorPurplePrimary)) {
            setTheme(R.style.PurpleTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Purple);

        } else if (selectedColor == getResources().getColor(R.color.colorTealPrimary)) {
            setTheme(R.style.TealTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Teal);

        } else if (selectedColor == getResources().getColor(R.color.colorPinkPrimary)) {
            setTheme(R.style.PinkTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Pink);

        } else if (selectedColor == getResources().getColor(R.color.colorDeepPurplePrimary)) {
            setTheme(R.style.DeepPurpleTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.DeepPurple);

        } else if (selectedColor == getResources().getColor(R.color.colorOrangePrimary)) {
            setTheme(R.style.OrangeTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Orange);

        } else if (selectedColor == getResources().getColor(R.color.colorIndigoPrimary)) {
            setTheme(R.style.IndigoTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Indigo);

        } else if (selectedColor == getResources().getColor(R.color.colorLightGreenPrimary)) {
            setTheme(R.style.LightGreenTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.LightGreen);

        } else if (selectedColor == getResources().getColor(R.color.colorDeepOrangePrimary)) {
            setTheme(R.style.DeepOrangeTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.DeepOrange);

        } else if (selectedColor == getResources().getColor(R.color.colorLimePrimary)) {
            setTheme(R.style.LimeTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Lime);

        } else if (selectedColor == getResources().getColor(R.color.colorBlueGreyPrimary)) {
            setTheme(R.style.BlueGreyTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.BlueGrey);

        } else if (selectedColor == getResources().getColor(R.color.colorCyanPrimary)) {
            setTheme(R.style.CyanTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Cyan);

        }
        final View rootView = getWindow().getDecorView();
        rootView.setDrawingCacheEnabled(true);
        rootView.buildDrawingCache(true);

        final Bitmap localBitmap = Bitmap.createBitmap(rootView.getDrawingCache());
        rootView.setDrawingCacheEnabled(false);
        if (null != localBitmap && rootView instanceof ViewGroup) {
            final View tmpView = new View(getApplicationContext());
            tmpView.setBackgroundDrawable(new BitmapDrawable(getResources(), localBitmap));
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            ((ViewGroup) rootView).addView(tmpView, params);
            tmpView.animate().alpha(0).setDuration(400).setListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                    ColorUiUtil.changeTheme(rootView, getTheme());
                    System.gc();
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    ((ViewGroup) rootView).removeView(tmpView);
                    localBitmap.recycle();
                    homeAdapter.notifyDataSetChanged();
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            }).start();
            mCommonToolbar.setBackgroundColor(selectedColor);
        }
    }
    private void initAdapter() {
        ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(3, 2));
//        homeAdapter.openLoadAnimation();
        //View top = getLayoutInflater().inflate(R.layout.top_view, (ViewGroup) mRecyclerView.getParent(), false);
        //homeAdapter.addHeaderView(top);
        homeAdapter.setOnItemClickListener((adapter, view, position) -> {

            //Intent intent = new Intent(getContext(), ACTIVITY[position]);
            try {
                HomeItem homeItem = (HomeItem) adapter.getItem(position);
                assert homeItem != null;
                Intent intent = new Intent(this, TaskActivity.class);
                intent.putExtra(DataKeys.HOME_ITEM.name(),homeItem);
                startActivityForResult(intent,this.REQUEST_CODE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        mRecyclerView.setAdapter(homeAdapter);
        ArmsUtils.configRecyclerView(rvMeue, new LinearLayoutManager(this));
        menuAdapter = new MenuAdapter(Arrays.asList("选择日志级别","检测更新","设置","帮助文档"));
        menuAdapter.setOnItemClickListener(((adapter, view, position) -> {
            switch (position){
                case 0:
                    dialog.show();
                    break;
                case 1:
                    checkUpdate();
                    break;
                case 2:
                    Intent intent = new Intent(this, SettingsActivity.class);
                    startActivityForResult(intent,SETTING_REQUEST_CODE);
                    break;
                case 3:
                    startActivity(new Intent(this,TestViewActivity.class));
                    break;
            }
        }));
        rvMeue.setAdapter(menuAdapter);

    }
    @Override
    public void onColorChooserDismissed(@NonNull ColorChooserDialog dialog) {
            dialog.dismiss();
    }

    private void initLogMenue(){
        int level = SharedPreUtils.getInstance().getInt(ConfigKeys.XLOG_LEVEL.name(),LogLevel.ERROR);
        final List<String> mData = Arrays.asList("OFF", "VERBOSE", "DEBUG", "INFO", "WARN", "ERROR");
        if(level> 6){
            level =1;
        }

        LogLevelAdapter<String> logLevelAdapter = new LogLevelAdapter<String>(mData,this);
        dialog = DialogPlus.newDialog(this)
                //.setContentHolder(new ViewHolder(R.layout.dialog_dispensing))
                .setContentBackgroundResource(R.drawable.dialog_menu_style)
                .setHeader(R.layout.botton_dialog)
                .setAdapter(logLevelAdapter)
                //.setExpanded(true,250)  // This will enable the expand feature, (similar to android L share dialog)
                .setGravity(Gravity.BOTTOM )
                //.setCancelable(false)
                //.setOverlayBackgroundResource(R.drawable.dialog_menu_style)
                .setInAnimation(R.anim.dialog_in)
                .setOutAnimation(R.anim.dialog_out)
                .setOnItemClickListener( ( dialog, item,  view, position) -> {
                    if (position == 0) {
                        menuAdapter.setLogName("OFF");
                        XLog.init(LogLevel.NONE);
                        SharedPreUtils.getInstance().putInt(ConfigKeys.XLOG_LEVEL.name(), LogLevel.NONE);
                    } else {
                        menuAdapter.setLogName(LogLevel.getLevelName(position + 1));
                        XLog.init(position+1);
                        SharedPreUtils.getInstance().putInt(ConfigKeys.XLOG_LEVEL.name(), position+1);
                    }
                    ((AppCompatCheckedTextView) view.findViewById(com.chcit.custom.view.R.id.text1)).setChecked(true);
                    logLevelAdapter.setSelected(position);
                    dialog.dismiss();
                    menuAdapter.notifyItemChanged(0);
                })
                .create();
        ListView listView = dialog.getHolder().getListView();
        listView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
        listView.setDivider(getResources().getDrawable(R.drawable.item_drivide));
        listView.setDividerHeight(1);
        logLevelAdapter.setSelected(level-1);
        menuAdapter.setLogName(LogLevel.getLevelName(level));
        menuAdapter.notifyItemChanged(0);
      /*  DialogMenu dialogMenu = new DialogMenu(this, Gravity.BOTTOM, mData);
        dialogMenu.setOnItemClickListener( position -> {
            if (position == 0) {
                tvLogLevel.setText("OFF");
                XLog.init(LogLevel.NONE);
                SharedPreUtils.getInstance().putInt(ConfigKeys.XLOG_LEVEL.name(), LogLevel.NONE);
            } else {
                tvLogLevel.setText(LogLevel.getLevelName(position + 1));
                XLog.init(position+1);
                SharedPreUtils.getInstance().putInt(ConfigKeys.XLOG_LEVEL.name(), position+1);
            }
        });*/


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            mCommonToolbar.setTitleText(HttpClientHelper.getSelectWareHouse().getName());
            if(onTaskOFF){
                mPresenter.start();
            }

        }else if(requestCode == SETTING_REQUEST_CODE && resultCode == RESULT_OK){
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            onTaskOFF =prefs.getBoolean("do_task", true);
            if(onTaskOFF){
                mPresenter.start();
            }else{
                for(HomeItem item: homeAdapter.getData()){
                    item.setTaskNumber(0);
                }
                homeAdapter.notifyDataSetChanged();
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(onTaskOFF&&mPresenter!=null){
            mPresenter.stop();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(onTaskOFF&&mPresenter!=null) {
            mPresenter.start();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(onTaskOFF&&mPresenter!=null) {
            mPresenter.stop();
        }
    }

    @Override
    public void onEnterAnimationComplete() {
        super.onEnterAnimationComplete();


    }


}
